<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\notify\gateway;

use app\common\model\Goods;
use app\common\model\Level;
use app\common\model\Order;
use app\common\model\PurchaseRecord;
use app\common\model\User;
use app\common\model\VipExpires;
use think\Db;
use think\Exception;

class Purchase
{
    public function dealWith($response,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {
            //file_put_contents('recharge.txt','step:1',FILE_APPEND);
            if (!$orderInfo = Order::where('order',$response['out_trade_no'])->find()){
                throw new Exception('当前记录不存在');
            }
            //file_put_contents('recharge.txt','step:2',FILE_APPEND);
            if ($orderInfo['pay_state'] != Order::PAY_STATE_INIT){
                throw new Exception('当前订单已处理');
            }
            //file_put_contents('recharge.txt','step:3',FILE_APPEND);
            if ($response['result_code'] == 'SUCCESS') {
                //file_put_contents('recharge.txt','step:4',FILE_APPEND);
                if(!Order::update([
                    'trilateral_pay_order'=>$response['transaction_id'],
                    'pay_date'=>strtotime($response['time_end']),
                    'up_date'=>time(),
                    'pay_state'=>Order::PAY_STATE_SUCCESS
                ],['po_id'=>$orderInfo['po_id']])){
                    throw new Exception('订单更新失败');
                }
                //file_put_contents('recharge.txt','step:5',FILE_APPEND);
                $purchaseRecord = PurchaseRecord::where('order',$response['out_trade_no'])->find();
                if (!$purchaseRecord){
                    throw new Exception('未找到购买相关订单信息');
                }
                if(!PurchaseRecord::update([
                    'update_time'=>time(),
                    'status'=>PurchaseRecord::STATUS_SUCCESS
                ],['order'=>$response['out_trade_no']])){
                    throw new Exception('订单更新失败');
                }

                $goodsInfo = Goods::where('g_id',$purchaseRecord['goods_id'])->find();
                if (!$goodsInfo){
                    throw new Exception('当前商品信息不存在');
                }
                $levelInfo = Level::where('vl_id',$goodsInfo['level_id'])->find();
                if (!$levelInfo){
                    throw new Exception('当前订单等级信息不存在');
                }
                $vipExpiresInfo = VipExpires::where('user_id',$orderInfo['user_id'])->where('level',$levelInfo['vl_id'])->find();
                $result = false;
                $startTime = strtotime(date('Y-m-d'));
                if(!$vipExpiresInfo){
                    $insert = [
                        'user_id'=>$orderInfo['user_id'],
                        'level'=>$levelInfo['vl_id'],
                        'level_sort'=>$levelInfo['sort'],
                        'start_date'=>$startTime,
                        'end_date'=>$startTime+($goodsInfo['validity_period']*3600*24),
                        'create_time'=>time(),
                    ];
                    $result = VipExpires::create($insert);
                }else{
                    $result = VipExpires::where('user_id',$orderInfo['user_id'])->where('level',$levelInfo['vl_id'])->update([
                        'end_date'=>Db::raw('end_date + '.($goodsInfo['validity_period']*3600*24))
                    ]);
                }

                if (!$result){
                    throw new Exception('当前订单更新失败');
                }

                $vipUser = VipExpires::where('user_id',$orderInfo['user_id'])->order('level_sort desc')->find();
                if(!User::where('id',$orderInfo['user_id'])->update([
                    'temp_level'=>$vipUser['level'] ?? $levelInfo['vl_id'],
                    'updatetime'=>time(),
                ])){
                    throw new Exception('用户信息更新失败');
                }
            }

            if ($isTrans)
                Db::commit();
            return ['code'=>1,'message'=>'success'];
        }catch (Exception $exception){
            file_put_contents('recharge.txt','exception:'.$exception->getMessage(),FILE_APPEND);
            if ($isTrans)
                Db::rollback();
            return ['code'=>0,'message'=>$exception->getMessage()];
        }
    }
}